import re, random, regex

def compile_chinese_code(code: str, keywords_map = {}) -> str:
    """编译函数和类为python代码"""
    # 生成占位符
    def zwfhq():
        length = 1
        while True:
            zwf = "<" + ''.join(chr(random.randint(0x9FFF, 0x10FFFF)) for _ in range(length)) + ">"
            if zwf not in code:
                break
            length += 1
        return zwf

    # 使用两个独立的映射
    quote_map = {}
    bracket_map = {}

    def replace_quotes(m):
        full = m.group(0)
        key = zwfhq()
        quote_map[key] = full
        return key

    def replace_brackets(m):
        full = m.group(0)
        key = zwfhq()
        bracket_map[key] = full
        return key

    # 第一步：replace引号和注释
    quote_pattern = re.compile(r'''
        (?P<dquote>"[^"\\]*(?:\\.[^"\\]*)*")     # 双引号
        |
        (?P<squote>'[^'\\]*(?:\\.[^'\\]*)*')     # 单引号
        |
        (?P<comment>\#.*)                        # 注释
        |
        (?P<walrus>:=)                           # 海象
    ''', re.X)

    # 第一步replace后（引号和注释）
    processed = quote_pattern.sub(replace_quotes, code)

    # 第二步：replace大括号中和括号
    bracket_pattern = regex.compile(r'''
        (?P<brace>\{(?:[^{}]|(?P>brace))*\})         # 递归匹配大括号
        |
        (?P<square>\[(?:[^\[\]]|(?P>square))*\])     # 递归匹配中括号
    ''', re.X)

    # 第二步replace后（大括号中和括号）
    processed = bracket_pattern.sub(replace_brackets, processed)

    # 去除反斜杠换行
    processed = processed.replace("\\\n", "")

    # 编译保留关键字
    for k, v in keywords_map.items():
        processed = processed.replace(k, v)


    # 编译 class
    lines = processed.splitlines(True)
    out = []
    for line in lines:
        match = re.match(
            r'^(\s*)(?!\b(?:if|else|elif|try|except|finally|while|for|with|def|class)\b)(\w+)\s*:(.*)$',
            line
        )
        if match:
            indent, name, tail = match.groups()
            out.append(f"{indent}class {name}:{tail}\n")
        else:
            out.append(line)
    processed = ''.join(out)

    # 编译 def
    def compile_functions(src: str) -> str:
        pattern = regex.compile(
            r"""(?smx)^([ \t]*)                     # 行首空白
            (async\s+)?                             # 1. 可选 async
            (\w+)                                   # 2. 真正的函数名
            (                                       # 3. 括号+类型+冒号
                \s*(?&b)\s*
                (?:\s*->[\s\S]*?)?
                \s*:
            )
            (?(DEFINE)(?<b>\((?:[^()]++|(?&b))*\)))
            """,
        )
        return pattern.sub(r'\1\2def \3\4', src)

    processed = compile_functions(processed)

    # 分阶段还原：先还原括号，再还原引号
    sorted_brackets = sorted(bracket_map.items(), key=lambda x: len(x[0]), reverse=True)
    for key, original in sorted_brackets:
        processed = processed.replace(key, original)

    sorted_quotes = sorted(quote_map.items(), key=lambda x: len(x[0]), reverse=True)
    for key, original in sorted_quotes:
        processed = processed.replace(key, original)

    return processed
